import React, {Component} from 'react';
// import PropTypes from "prop-types";
import axios from "axios";
import PubSub from "pubsub-js";

class Main extends Component {
    state = {
        initView: true,
        loading: false,
        users: null,
        errorMsg: null
    };

    componentDidMount() {
        PubSub.subscribe("search", async (msg, data) => {
            console.log(data);
            this.setState({
                initView: false,
                loading: true
            });
            const url = "https://api.github.com/search/users";
            let res = await axios.get(url, {
                params: {
                    q: data
                }
            });
            console.log(res.data);
            this.setState({
                loading: false,
                users: res.data.items
            })
        })
    }

    render() {
        const {initView, loading, users, errorMsg} = this.state;
        if (initView) {
            return (<h2>请输入关键字搜索!</h2>)
        } else if (loading) {
            return (<h2>正在请求中...</h2>)
        } else if (errorMsg) {
            return (<h2>{errorMsg}</h2>)
        } else if (users) {
            return (
                <div className="row">
                    {
                        users.map((val, index) => (
                            <div className="card" key={val.id}>
                                <a href={val.html_url} target="_blank">
                                    <img src={val.avatar_url}
                                         style={{width: "100px"}}/>
                                </a>
                                <p className="card-text">{val.login}</p>
                            </div>
                        ))
                    }
                </div>
            );
        }
    }
}

export default Main;